package com.sxu.douban.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Step1 {
    public static class mymapper extends Mapper<Object, Text, Text, Text> {
        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String line=value.toString();
            String u_id=line.split(",")[1];
            String m_id=line.split(",")[2];
            String type=line.split(",")[3];
            String rating=line.split(",")[4];
            context.write(new Text(u_id), new Text(m_id+"@"+type+":"+rating));
        }
    }

    public static class myreducer extends Reducer<Text, Text, Text, Text> {
        public void reduce(Text key, Iterable<Text> values, Context context)
                throws InterruptedException, IOException {
            String temp="";
            for(Text value:values){
                temp+=value.toString()+",";
            }
            context.write(key, new Text(temp));
        }
    }

    public static void run() throws IOException, ClassNotFoundException, InterruptedException {
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS","hdfs://192.168.22.131:9000");
        FileSystem fileSystem = FileSystem.get(configuration);
        Job job = Job.getInstance(configuration);
        job.setJarByClass(Step1.class);
        job.setMapperClass(Step1.mymapper.class);
        job.setReducerClass(Step1.myreducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        //用sqoop先从mysql拿出数据上传到hdfs
        // sqoop import --connect jdbc:mysql://192.168.22.189:3306/douban_movie --username root --password 123456 --table rating --m 1
        FileInputFormat.addInputPath(job, new Path("/user/root/rating/part-m-00000"));
        Path outPath = new Path("/Movie_Recommend/output1");
        if (fileSystem.exists(outPath)){
            fileSystem.delete(outPath,true);
        }
        FileOutputFormat.setOutputPath(job, outPath);
        job.waitForCompletion(true);
    }
}


